package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.dto.HistoryInfo;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.QueryWrapperUtils;
import com.sk.bilibili.utils.WarpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.History;
import com.sk.bilibili.mapper.HistoryMapper;

/**
 * @author 邵康
 * @date 2021/11/25 12:55
 */
@Service
public class HistoryService extends ServiceImpl<HistoryMapper, History> {

    @Autowired
    private WarpUtils warpUtils;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public R<Void> add(History history) {
        Integer memberId = BSessionUtils.getMemberId();
        history.setMemberId(memberId);
        if(memberService.openHistory(memberId)){
            QueryWrapper<History> queryWrapper = QueryWrapperUtils.eq("member_id", memberId,
                    "type", history.getType(), "target_id", history.getTargetId());
            remove(queryWrapper);
            save(history);
        }
        eventPublisher.publishEvent(new BiliBiliEvent<>(this,history));
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(History history) {
        updateById(history);
        return R.success();
    }

    public R<IPage<History>> pageSearch(HistoryInfo historyInfo) {
        QueryWrapper<History> queryWrapper = QueryWrapperUtils.eq("member_id",
                BSessionUtils.getMemberId());
        queryWrapper.orderByDesc("create_date");
        queryWrapper.like("title", historyInfo.getKeyword());
        handleType(historyInfo.getType(),queryWrapper);
        IPage<History> page = page(historyInfo.page(), queryWrapper);
        page.getRecords().forEach(history ->
                history.getExtra().addExtra(warpUtils.getTypeTarget(history.getType(),history.getTargetId())));
        return R.success(page);
    }

    private void handleType(Integer type, QueryWrapper<History> queryWrapper) {
        if(type==null)return;
        switch (type){
            case 0:queryWrapper.in("type",0,1);break;
            case 6:queryWrapper.eq("type",6);break;
            default:throw new RuntimeException("暂不支持的选择类型:"+type);
        }
    }

}
